package com.example.service;

import com.example.model.entity.Like;
import com.example.model.entity.Post;
import com.example.model.entity.User;
import com.example.repository.LikeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class LikeService {
    @Autowired
    private LikeRepository likeRepository;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private PostService postService;

    @Transactional
    public void likePost(Long userId, Long postId) {
        if (likeRepository.existsByUserIdAndPostId(userId, postId)) {
            throw new RuntimeException("已经点赞过了");
        }
        
        User user = userService.findById(userId);
        Post post = postService.findById(postId);
        
        Like like = new Like();
        like.setUser(user);
        like.setPost(post);
        like.setCreatedAt(LocalDateTime.now());
        
        likeRepository.save(like);
    }

    @Transactional
    public void unlikePost(Long userId, Long postId) {
        likeRepository.deleteByUserIdAndPostId(userId, postId);
    }

    public boolean hasLiked(Long userId, Long postId) {
        return likeRepository.existsByUserIdAndPostId(userId, postId);
    }
} 